<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\CreateCateRequest;
use App\Http\Requests\EditCateRequest;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;

/**
 * 视频分类控制器
 * Class CategoryController
 * @package App\Http\Controllers\Admin
 */
class CategoryController extends Controller
{
    /**
     * 视频分类列表
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $data = Category::get(['id', 'name']);
        return view('admin.cate.index', compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return view('admin.cate.create');
    }

    /**
     * 新增处理
     * @param CreateCateRequest $request
     * @return array
     */
    public function store(CreateCateRequest $request)
    {
        $name = $request->only(['name']);
        $res = Category::create($name);
        if ($res) return ['status' => 0, 'msg' => '成功'];
        return ['status' => 1, 'msg' => '失败'];
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return Response
     */
    public function edit($id)
    {
        $data = Category::find($id);
        return view('admin.cate.edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param EditCateRequest $request
     * @param  int $id
     * @return array
     */
    public function update(EditCateRequest $request, $id)
    {
        $data = $request->only(['name']);
        $res = Category::where('id', $id)->update($data);
        if ($res) return ['status' => 0, 'msg' => '成功'];
        return ['status' => 1, 'msg' => '失败'];
    }

    /**
     * 删除
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return array
     * @throws \Exception
     */
    public function destroy(int $id)
    {
        $res = Category::where('id', $id)->delete();
        if ($res) return ['status' => 0, 'msg' => '成功'];
        return ['status' => 1, 'msg' => '失败'];
    }

    /**
     * 根据分类获取课程列表
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(int $id)
    {
        return response()->json(Category::with('courses')->find($id)->toArray()['courses']);
    }
}
